package com.inspectortime.webapp.util;

import java.util.Collection;

import org.springframework.util.StringUtils;

import com.inspectortime.domain.RealEstateAgent;

/**
 * A place to put shared code that is specific to Inspector Time's biz logic
 * and that doesn't really fit anywhere else. 
 *  
 * TODO:  Probably could find a better place to put the code, but I was strapped for ideas.  
 * Or at least we could come up with a more description name for the class.
 * 
 * @author bones
 *
 */
public class DomainUtils {

	/**
	 * Parses the value from the auto-completing Realtor dropdown (in schedule wizard and edit inspection)
	 * and finds the matching realtor from the passed in collection of agents
	 * 
	 * Expects value to be in format "last, first - company" (with " - company" being optional)
	 * 
	 * @param value the name/company of the Real Estate Agent (in a specific format)
	 * @param realors Collection of realtors in which to find the named realtor
	 * @return
	 */
	public static RealEstateAgent getExistingRealtorByAutoCompletionName(String value, Collection<RealEstateAgent> realtors) {

		if (value.indexOf(",") < 0) {
			return null;
		}

		String[] firstSplit = value.split(",");
		String lastName = firstSplit[0].trim();
		String firstName = null;
		String company = null;

		if (firstSplit[1].indexOf("-") > 0) {
			String[] secondSplit = firstSplit[1].split("-");
			firstName = secondSplit[0].trim();
			company = secondSplit[1].trim();
		} else {
			firstName = firstSplit[1].trim();
		}

		for (RealEstateAgent realtor : realtors) {
			if (realtor.getName().getFirst().equalsIgnoreCase(firstName)
					&& realtor.getName().getLast().equalsIgnoreCase(lastName)) {
				if (StringUtils.hasText(company)
						&& !company.equalsIgnoreCase(realtor.getCompany())) {
					// ignore
				} else {
					return realtor;
				}
			}
		}

		return null;
	}
}
